package com.turing.post.organization.impl;

import java.math.BigInteger;
import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.organization.util.Merchant;
import com.turing.post.organization.util.MerchantDao;
import com.turing.post.util.Config;
import com.turing.post.util.GeneralDao;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;
import com.turing.post.util.PCPSWebInput;

/**
 * 商户业务实现
 * 
 * @author zxp
 * @Dec 19, 2012
 */
@Stateless(mappedName = "organization.impl.MerchantDaoImpl")
@Remote
@Local
public class MerchantDaoImpl implements MerchantDao {
	/**
	 * 实体管理器
	 */
	@PersistenceContext
	protected EntityManager _em;

	@SuppressWarnings("unchecked")
	@Override
	public Merchant getMerchantByMerchantName(String merchantName) {
		String jpql = "select * from Merchant c where c.MerchantName = ?1";
		Query query = _em.createNativeQuery(jpql, Merchant.class);
		query.setParameter(1, merchantName);
		List<Merchant> list = query.getResultList();
		if (list == null || list.isEmpty() || list.size() < 1) {
			return null;
		}
		return list.get(0);
	}

	@Override
	public Merchant getMerchantByMerchantNo(String merchantNo) {
		return _em.find(Merchant.class, merchantNo);
	}

	@Override
	public Merchant getMerchantForUpdate(String merchantNo) {
		String jpql = "select * from Merchant c where c.merchantNo = ?1 for update";
		Query query = _em.createNativeQuery(jpql, Merchant.class);
		query.setParameter(1, merchantNo);
		return (Merchant) query.getSingleResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Merchant> getMerchantList(PCPSWebInput webInput,
			String merchantNo, String merchantName, BigInteger merchantTypeId,
			BigInteger incomeBranchId, String channelMode, String regionNo,
			Integer page) {
		String sql = "select * from Merchant t where 1=1";
		if (!PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
			String issueCompanyNo = PCPSUtil.getIssueCompanyNo(webInput);
			sql = sql + " and IssueCompanyNo='" + issueCompanyNo + "'";
		}
		sql = sql
				+ " and MerchantNo like ?1 "
				+ "and MerchantName like ?4 "
				+ " and (?2=0 or IncomeBranchId =?2) "
				+ " and (?3 = '*' or channelMode =?3) "
				+ " and (?5 is null or RegionNo like ''||?5||'%') order by MerchantNo";
		int maxResult = Config.PAGE_SIZE;
		int startPosition = maxResult * page;
		Query query = _em.createNativeQuery(sql, Merchant.class)
				.setFirstResult(startPosition).setMaxResults(maxResult);
		if (PCPSUtil.isEmpty(merchantNo)) {
			merchantNo = "";
		}
		query.setParameter(1, "%" + merchantNo + "%");
		query.setParameter(2, incomeBranchId);
		query.setParameter(3, channelMode);
		if (PCPSUtil.isEmpty(merchantName)) {
			merchantName = "";
		}
		query.setParameter(4, "%" + merchantName + "%");
		query.setParameter(5, regionNo);
		return query.getResultList();
	}

	@Override
	public BigInteger getMerchantTotal(PCPSWebInput webInput,
			String merchantNo, String merchantName, BigInteger merchantTypeId,
			BigInteger incomeBranchId, String channelMode, String regionNo) {
		String sql = "select nvl(count(*),0) from Merchant t where 1=1";
		if (!PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
			String issueCompanyNo = PCPSUtil.getIssueCompanyNo(webInput);
			sql = sql + " and IssueCompanyNo='" + issueCompanyNo + "'";
		}
		sql = sql + " and MerchantNo like ?1 " + "and MerchantName like ?4 "
				+ " and (?2=0 or IncomeBranchId =?2) "
				+ " and (?3 = '*' or channelMode =?3) "
				+ " and (?5 is null or RegionNo like ''||?5||'%')";
		Query query = _em.createNativeQuery(sql);
		if (PCPSUtil.isEmpty(merchantNo)) {
			merchantNo = "";
		}
		query.setParameter(1, "%" + merchantNo + "%");
		query.setParameter(2, incomeBranchId);
		query.setParameter(3, channelMode);
		if (PCPSUtil.isEmpty(merchantName)) {
			merchantName = "";
		}
		query.setParameter(4, "%" + merchantName + "%");
		query.setParameter(5, regionNo);
		return new BigInteger(query.getSingleResult().toString());
	}

	@Override
	public void insertMerchant(Merchant merchant)
			throws PCPSApplicationException {
		GeneralDao.insert(_em, merchant);
	}

	@Override
	public void updateMerchant(Merchant merchant)
			throws PCPSApplicationException {
		GeneralDao.update(_em, merchant);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Merchant> getMerchantListByIssueCompanyNo(String issueCompanyNo) {
		String jpql = "select c.* from Merchant c where c.IssueCompanyNo = ?1 order by merchantno";
		Query query = _em.createNativeQuery(jpql, Merchant.class);
		query.setParameter(1, issueCompanyNo);
		return query.getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Merchant> getActivateMerchantListByIssueCompanyNo(String issueCompanyNo) {
		String jpql = "select c.* from Merchant c where c.IssueCompanyNo = ?1 and c.activate='1' order by merchantno";
		Query query = _em.createNativeQuery(jpql, Merchant.class);
		query.setParameter(1, issueCompanyNo);
		return query.getResultList();
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Object[]> getMerchantReport(PCPSWebInput webInput) {
		if (webInput == null || PCPSUtil.isEmpty(webInput.getOperBranchNo()))
			return null;
		String sql = "select m.merchantno merchantno,m.merchantname merchantname,"
				+ "(select i.industryname from industry i where oc.industryid is not null and i.industryid = oc.industryid) industry,"
				+ "mc.settcycle settlementcycle,mc.Policy Policy,mfp.feeratio," 
				+ "mfp.limitamount,mfp.floatfeeratio floatfeeratio,mc.StartDate policystartdate,mc.EndDate policyenddate,mfp.FeePolicyName "
				+ "from merchant m " 
				+ "left join merchantcontract mc on m.merchantno=mc.merchantno and mc.startdate <= sysdate and mc.enddate >= sysdate " 
				+ "left join organizecustom oc on m.organizeid = oc.organizeid "  
				+ "left join merchantfeesettlementpolicy mfp on mfp.contractid = mc.contractid "
				+ "where m.issuecompanyno=?1  and mc.status = '2' and mfp.status = '1' order by m.merchantno";
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, PCPSUtil.getIssueCompanyNo(webInput));
		List<Object[]> list = query.getResultList();
		return list;
	}

	/**
	 * 根据渠道模式检索商户清单
	 * 
	 * @param channelMode
	 *            渠道模式
	 * @param webInput
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Merchant> getMerchantByChannelMode(PCPSWebInput webInput,
			String channelMode) {
		if (webInput == null)
			return null;
		String issueCompanyNo = PCPSUtil.getIssueCompanyNo(webInput);
		String sql = "select * from Merchant where IssueCompanyNo = ?1 " +
				" and (?2 is null or channelMode = ?2) " +
				" order by MerchantNo asc";
		Query query = _em.createNativeQuery(sql, Merchant.class);
		query.setParameter(1, issueCompanyNo);
		query.setParameter(2, channelMode);
		return query.getResultList();
	}

	/**
	 * 根据商户编号检索商户名称
	 * 
	 * @param webInput
	 * @param merchantno
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Object[]> getMerchantList(PCPSWebInput webInput,
			String merchantno) {
		String issuecompanyno = PCPSUtil.getIssueCompanyNo(webInput);
		String sql = "select distinct(a.MerchantNo),b.merchantname from MerchantDaySettlement a,Merchant b  where a.merchantno=b.merchantno  and a.IssueCompanyNo='"
				+ issuecompanyno + "'";
		if (!PCPSUtil.isEmpty(merchantno))
			sql = sql + " and a.MerchantNo='" + merchantno + "'";
		sql = sql + " order by a.MerchantNo";
		Query query = _em.createNativeQuery(sql);
		List<Object[]> obj_list = query.getResultList();
		return obj_list;
	}

	@Override
	public String getAutoMerchantNo(String issueCompanyNo, String regionNo) {
		if (PCPSUtil.isEmpty(issueCompanyNo) || PCPSUtil.isEmpty(regionNo)) {
			return "";
		} else {
			String sql = "select nvl(max(substr(t.merchantno,8,4)),0)+1 from merchant t where substr(t.merchantno,0,6)=?1 and t.regionno=?2";
			Query query = _em.createNativeQuery(sql);
			query.setParameter(1, issueCompanyNo);
			query.setParameter(2, regionNo);
			return String.format("%04d", Integer.parseInt(query
					.getSingleResult().toString()));
		}
	}

	/**
	 * 验证商户名称重复
	 * 
	 * @param issuecompanyno
	 */
	public Integer IsMerchantName(String issueCompanyNo, String merchantName,
			String merchantNo) {
		if (PCPSUtil.isEmpty(merchantName) || PCPSUtil.isEmpty(issueCompanyNo))
			return 1;
		String sql = "select nvl(count(*),0) from Merchant where IssueCompanyNo=?1 and merchantName=?2 and ( merchantNo != ?3 or ?3 is NULL )";
		// if(!PCPSUtil.isEmpty(merchantNo))
		// sql=sql+" and merchantNo!='"+merchantNo+"'";
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, issueCompanyNo);
		query.setParameter(2, merchantName);
		if (PCPSUtil.isEmpty(merchantNo))
			query.setParameter(3, null);
		else
			query.setParameter(3, merchantNo);
		return Integer.parseInt(query.getSingleResult().toString());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Merchant> getMerchantByDevelopBranchNo(String developBranchNo) {
		String sql = "SELECT * FROM MERCHANT M WHERE (M.DEVELOPBRANCHNO IN (SELECT S.SUBBRANCHNO FROM SYSBRANCHSUBORD S WHERE S.BRANCHNO = ?1) OR M.DEVELOPBRANCHNO = ?1)";
		Query query = _em.createNativeQuery(sql, Merchant.class);
		query.setParameter(1, developBranchNo);
		return query.getResultList();
	}
}